<template>
  <div class="mail-login-page">
    <!-- 顶部导航 -->
    <header class="top-nav">
      <div class="nav-container">
        <div class="nav-left">
          <img
            src="@/assets/images/logo.png"
            alt="贵港文旅+"
            class="nav-logo"
          />
          <div class="brand-wrapper">
            <span class="brand-name">贵港文旅+</span>
            <span class="brand-pinyin">GUIGANGWENLV+</span>
          </div>
          <span class="divider">|</span>
          <span class="nav-title">你的专业文旅助手</span>
        </div>
        <div class="nav-right">
          <router-link to="/" class="nav-link">贵港文旅首页</router-link>
          <router-link to="/download/app" class="nav-link"
            >手机App下载</router-link
          >
          <router-link to="/download/desktop" class="nav-link"
            >电脑客户端下载</router-link
          >
          <router-link to="/merchant/apply" class="nav-link"
            >商家入驻</router-link
          >
          <router-link to="/help/guide" class="nav-link">帮助</router-link>
          <router-link to="/feedback" class="nav-link">反馈</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="main-content">
      <div class="login-container">
        <div class="login-box">
          <!-- 登录方式切换 -->
          <div class="login-type-switch">
            <div class="switch-container">
              <div class="switch-track">
                <div
                  class="switch-slider"
                  :style="{
                    transform: `translateX(${loginType === 'account' ? '100%' : '0'})`,
                  }"
                />
                <div
                  class="switch-option"
                  :class="{ active: loginType === 'qrcode' }"
                  @click="handleSwitchType('qrcode')"
                >
                  <icon-qrcode class="text-2xl" />
                  <span>扫码登录</span>
                </div>
                <div
                  class="switch-option"
                  :class="{ active: loginType === 'account' }"
                  @click="handleSwitchType('account')"
                >
                  <el-icon><User /></el-icon>
                  <span>账号登录</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 扫码登录 -->
          <template v-if="loginType === 'qrcode'">
            <div class="qrcode-login">
              <div class="qrcode-container">
                <div v-if="qrcodeLoading" class="qrcode-placeholder">
                  <icon-loading class="qrcode-icon" />
                  <span class="qrcode-text">二维码加载中...</span>
                </div>
                <div v-else-if="currentQrcode">
                  <div v-if="currentScanType === '微信'" id="wx-qrcode-container" class="qrcode-image">
                    <img v-if="qrcodeDataUrl" :src="qrcodeDataUrl" alt="微信扫码登录" class="real-qrcode">
                  </div>
                  <div v-else-if="currentScanType === 'QQ'" id="qq-qrcode-container" class="qrcode-image">
                    <img v-if="qrcodeDataUrl" :src="qrcodeDataUrl" alt="QQ扫码登录" class="real-qrcode">
                  </div>
                  <div v-else-if="currentScanType === '抖音'" id="douyin-qrcode-container" class="qrcode-image">
                    <img v-if="qrcodeDataUrl" :src="qrcodeDataUrl" alt="抖音扫码登录" class="real-qrcode">
                  </div>
                </div>
                <div class="qrcode-mask" v-if="qrcodeExpired">
                  <p>二维码已过期</p>
                  <el-button type="primary" @click="refreshQRCode">点击刷新</el-button>
                </div>
              </div>
              <p class="qrcode-tip">请使用{{ currentScanType }}扫一扫登录</p>
              <div class="scan-options">
                <div
                  v-for="type in scanTypes"
                  :key="type.name"
                  class="scan-option"
                  :class="[
                    type.className,
                    { active: currentScanType === type.name },
                  ]"
                  @click="switchScanType(type)"
                >
                  <div class="scan-icon-wrapper">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      :viewBox="type.viewBox"
                      class="scan-icon"
                      :class="type.iconClass"
                    >
                      <path :d="type.iconPath" />
                    </svg>
                  </div>
                  <span>{{ type.name }}</span>
                </div>
              </div>
            </div>
          </template>

          <!-- 账号密码登录 -->
          <el-form
            v-else
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @keyup.enter="handleLogin"
          >
            <el-form-item
              :prop="accountType === 'email' ? 'email' : 'phone'"
              class="account-form-item"
            >
              <div class="flex gap-3 w-full">
                <el-input
                  v-model="loginForm[accountType]"
                  :placeholder="
                    accountType === 'email'
                      ? '请输入邮箱账号'
                      : '请输入手机号码'
                  "
                  :prefix-icon="accountType === 'email' ? Message : Phone"
                  clearable
                  class="account-input flex-1"
                />
                
                <!-- 账号类型选择器，始终显示 -->
                <el-select
                  v-model="accountType"
                  class="account-type-select"
                  :popper-class="'account-type-select-dropdown'"
                  popper-append-to-body
                >
                  <el-option label="邮箱账号" value="email">
                    <div class="select-option-content">
                      <el-icon><Message /></el-icon>
                      <span>邮箱账号</span>
                    </div>
                  </el-option>
                  <el-option label="手机号码" value="phone">
                    <div class="select-option-content">
                      <el-icon><Phone /></el-icon>
                      <span>手机号码</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>

            <template v-if="loginMode === 'password'">
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="密码"
                  :prefix-icon="Lock"
                  clearable
                  show-password
                />
              </el-form-item>
            </template>
            <template v-else>
              <!-- 验证码模式 -->
              <el-form-item prop="verificationCode" class="mb-2 verification-item">
                <div class="verification-code-input">
                  <input
                    v-for="(digit, index) in 6"
                    :key="index"
                    :ref="
                      (el) => {
                        if (el) codeInputs[index] = el;
                      }
                    "
                    v-model="verificationDigits[index]"
                    type="text"
                    maxlength="1"
                    class="code-digit"
                    @input="handleCodeInput(index)"
                    @keydown.delete="handleCodeDelete(index)"
                    @keydown.left="focusInput(index - 1)"
                    @keydown.right="focusInput(index + 1)"
                    :disabled="loading"
                  />
                </div>
              </el-form-item>
            </template>

            <div class="form-options">
              <template v-if="loginMode === 'password'">
                <el-checkbox
                  v-model="loginForm.remember"
                  class="remember-checkbox"
                  >记住密码</el-checkbox
                >
              </template>
              <template v-else>
                <el-checkbox
                  v-model="loginForm.autoLogin"
                  class="auto-login-checkbox"
                  >30天内免登录</el-checkbox
                >
              </template>
              <div 
                class="verification-login-switch" 
                @click="switchLoginMode"
              >
                {{ loginMode === 'password' ? '验证码登录' : '账号密码登录' }}
              </div>
            </div>

            <div v-if="loginMode === 'verification' && false" class="verification-tip-box">
              <el-icon class="tip-icon"><InfoFilled /></el-icon>
              <span class="tip-text">验证码将发送到您的手机，请注意查收</span>
            </div>

            <!-- 密码模式显示登录按钮 -->
            <el-button
              v-if="loginMode === 'password'"
              type="primary"
              class="login-btn"
              size="large"
              :loading="loading"
              @click="handleLogin"
            >
              登 录
            </el-button>

            <!-- 验证码模式显示发送验证码按钮 -->
            <el-button
              v-else
              type="primary"
              class="login-btn"
              size="large"
              :loading="loading || timer"
              :disabled="timer"
              @click="handleSendVerificationCode"
            >
              <span v-if="timer">{{ countdown }}秒后可重新发送</span>
              <span v-else>发送验证码</span>
            </el-button>

            <div class="form-footer">
              <router-link to="/register" class="register-link"
                >注册新账号</router-link
              >
              <router-link to="/forgot-password" class="forgot-link"
                >忘记密码?</router-link
              >
            </div>
          </el-form>

          <!-- 统一的协议部分 -->
          <div class="terms-agreement">
            <template v-if="loginType === 'account'">
              <div class="checkbox-wrapper">
                <el-tooltip
                  content="请先阅读并同意服务条款和隐私政策"
                  placement="top"
                  :show-after="0"
                  :hide-after="3000"
                  :visible="showAgreementTip"
                  popper-class="agreement-tooltip"
                >
                  <div class="checkbox-wrapper">
                    <el-checkbox
                      v-model="agreedToTerms"
                      class="terms-checkbox"
                      @change="handleAgreementChange"
                    >
                      我已阅读并同意
                    </el-checkbox>
                  </div>
                </el-tooltip>
              </div>
              <a
                href="#"
                class="terms-link"
                @click.prevent="showServiceAgreement = true"
                >《服务条款》</a
              >
              和
              <a
                href="#"
                class="terms-link"
                @click.prevent="showPrivacyAgreement = true"
                >《隐私政策》</a
              >
            </template>
            <template v-else>
              <p class="text-sm text-gray-500 dark:text-gray-400">
                扫码视为同意
                <a
                  href="#"
                  class="terms-link"
                  @click.prevent="showServiceAgreement = true"
                  >《服务条款》</a
                >
                和
                <a
                  href="#"
                  class="terms-link"
                  @click.prevent="showPrivacyAgreement = true"
                  >《隐私政策》</a
                >
                <span class="block mt-1 text-gray-400 dark:text-gray-500"
                  >首次登录将自动注册</span
                >
              </p>
            </template>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="page-footer">
      <div class="footer-info">
        <span>贵港文旅版权所有 ©2024</span>
        <a href="#" class="footer-link">ICP备案 桂B2-20240101</a>
        <a href="#" class="footer-link">
          <img
            src="@/assets/images/police-badge.png"
            class="police-badge"
            alt="警徽"
          />
          桂公网安备 45010602006299号
        </a>
        <a href="#" class="footer-link">增值电信业务经营许可证 桂B2-20240101</a>
      </div>
    </footer>

    <AgreementDialog
      v-model="showServiceAgreement"
      type="user-service"
      @agree="handleServiceAgree"
    />

    <AgreementDialog
      v-model="showPrivacyAgreement"
      type="privacy"
      @agree="handlePrivacyAgree"
    />

    <CompleteInfoDialog
      v-model="showCompleteInfo"
      :userInfo="tempUserInfo"
      @complete="handleCompleteInfo"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted, onMounted, watch, nextTick, computed } from "vue";
import {
  User,
  Lock,
  Phone,
  Key,
  Location,
  Guide,
  Shop,
  Monitor,
  Platform,
  QrCode,
  Message,
  Promotion,
  ChatDotSquare,
  VideoPlay,
  Loading,
  InfoFilled,
} from "@element-plus/icons-vue";
import {
  IconQrcode,
  IconScan,
  IconLoading,
  IconWechat,
  IconMessage,
} from "@arco-design/web-vue/es/icon";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import AgreementDialog from "@/components/merchantapply/AgreementDialog.vue";
import CompleteInfoDialog from "@/components/auth/CompleteInfoDialog.vue";
import QRCode from 'qrcode';
import request from "@/api/axios"; // 导入 axios 实例
import { getPhoneVerificationCode, getEmailVerificationCode } from "@/api/auth"; // 导入获取验证码的API

// 路由与状态管理
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 表单与UI状态管理
const loginFormRef = ref(null);
const loading = ref(false);
const loginType = ref("account");
const accountType = ref("email");

// 协议相关状态
const agreedToTerms = ref(false);
const showAgreementTip = ref(false);
const showServiceAgreement = ref(false);
const showPrivacyAgreement = ref(false);
const agreedToService = ref(false);
const agreedToPrivacy = ref(false);

// 二维码相关状态
const qrcodeLoading = ref(false);
const timer = ref(null);
const countdown = ref(0);
const qrcodeExpired = ref(false);
const currentScanType = ref("微信");
const currentQrcode = ref(null);
const qrcodeDataUrl = ref('');
const pollingTimer = ref(null);

// 用户信息相关
const showCompleteInfo = ref(false);
const tempUserInfo = ref(null);

// 登录模式
const loginMode = ref('password');

// 添加验证码相关的数据
const codeInputs = ref([]);
const verificationDigits = ref(["", "", "", "", "", ""]);

// 扫码类型配置
const scanTypes = [
  {
    name: "微信",
    className: "wechat-scan-option",
    viewBox: "0 0 576 512",
    iconPath:
      "M385.2 167.6c6.4 0 12.6 .3 18.8 1.1C387.4 90.3 303.3 32 207.7 32 100.5 32 13 104.8 13 197.4c0 53.4 29.3 97.5 77.9 131.6l-19.3 58.6 68-34.1c24.4 4.8 43.8 9.7 68.2 9.7 6.2 0 12.1-.3 18.3-.8-4-12.9-6.2-26.6-6.2-40.8-.1-84.9 72.9-154 165.3-154zm-104.5-52.9c14.5 0 24.2 9.7 24.2 24.4 0 14.5-9.7 24.2-24.2 24.2-14.8 0-29.3-9.7-29.3-24.2 .1-14.7 14.6-24.4 29.3-24.4zm-136.4 48.6c-14.5 0-29.3-9.7-29.3-24.2 0-14.8 14.8-24.4 29.3-24.4 14.8 0 24.4 9.7 24.4 24.4 0 14.6-9.6 24.2-24.4 24.2zM563 319.4c0-77.9-77.9-141.3-165.4-141.3-92.7 0-165.4 63.4-165.4 141.3S305 460.7 397.6 460.7c19.3 0 38.9-5.1 58.6-9.9l53.4 29.3-14.8-48.6C534 402.1 563 363.2 563 319.4zm-219.1-24.5c-9.7 0-19.3-9.7-19.3-19.6 0-9.7 9.7-19.3 19.3-19.3 14.8 0 24.4 9.7 24.4 19.3 0 10-9.7 19.6-24.4 19.6zm107.1 0c-9.7 0-19.3-9.7-19.3-19.6 0-9.7 9.7-19.3 19.3-19.3 14.5 0 24.4 9.7 24.4 19.3 .1 10-9.9 19.6-24.4 19.6z",
    iconClass: "wechat-icon",
  },
  {
    name: "QQ",
    className: "qq-scan-option",
    viewBox: "0 0 448 512",
    iconPath:
      "M433.754 420.445c-11.526 1.393-44.86-52.741-44.86-52.741 0 31.345-16.136 72.247-51.051 101.786 16.842 5.192 54.843 19.167 45.803 34.421-7.316 12.343-125.51 7.881-159.632 4.037-34.122 3.844-152.316 8.306-159.632-4.037-9.045-15.25 28.918-29.214 45.783-34.415-34.92-29.539-51.059-70.445-51.059-101.792 0 0-33.334 54.134-44.859 52.741-5.37-.65-12.424-29.644 9.347-99.704 10.261-33.024 21.995-60.478 40.144-105.779C60.683 98.063 108.982.006 224 0c113.737.006 163.156 96.133 160.264 214.963 18.118 45.223 29.912 72.85 40.144 105.778 21.768 70.06 14.716 99.053 9.346 99.704z",
    iconClass: "qq-icon",
  },
  {
    name: "抖音",
    className: "tiktok-scan-option",
    viewBox: "0 0 448 512",
    iconPath:
      "M448 209.9a210.1 210.1 0 0 1 -122.8-39.3V349.4A162.6 162.6 0 1 1 185 188.3V278.2a74.6 74.6 0 1 0 52.2 71.2V0l88 0a121.2 121.2 0 0 0 1.9 22.2h0A122.2 122.2 0 0 0 381 102.4a121.4 121.4 0 0 0 67 20.1z",
    iconClass: "tiktok-icon",
  },
];

// 登录表单数据
const loginForm = reactive({
  email: "",
  phone: "",
  password: "",
  remember: false,
  verificationCode: "",
  autoLogin: false,
});

// 表单验证规则
const loginRules = {
  email: [
    { required: true, message: "请输入邮箱账号", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: ["blur", "change"],
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度应为6位", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "验证码应为6位数字", trigger: "blur" },
  ],
};

// 扫码登录的用户信息
const completeInfoForm = reactive({
  username: "",
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
  verificationCode: "",
});

// 使用计算属性确定当前登录使用的是邮箱还是手机号
const loginAccount = computed(() => {
  return accountType.value === "email" ? loginForm.email : loginForm.phone;
});

// 处理登录类型切换
const handleSwitchType = (type) => {
  loginType.value = type;
  if (type === 'qrcode') {
    // 切换到扫码登录时立即生成二维码
    nextTick(() => {
      switchScanType(scanTypes.find(t => t.name === currentScanType.value) || scanTypes[0]);
    });
  }
};

// 处理协议勾选变化
const handleAgreementChange = (val) => {
  if (val) {
    showAgreementTip.value = false;
  }
};

// 登录处理函数
const handleLogin = async () => {
  // 检查是否同意服务条款
  if (!agreedToTerms.value) {
    showAgreementTip.value = true;
    ElMessage.warning("请先阅读并同意服务条款和隐私政策");
    return;
  }

  // 如果是验证码登录模式，调用验证码登录方法
  if (loginMode.value === 'verification') {
    await handleVerificationLogin();
    return;
  }

  if (!loginFormRef.value) return;

  try {
    // 表单验证
    await loginFormRef.value.validate();
    loading.value = true;

    // 构建登录数据
    const loginData = buildLoginData();

    // 登录逻辑处理
    const { success, userData } = await performLogin(loginData);

    // 登录成功后处理
    if (success) {
      handleLoginSuccess(userData);
    }
  } catch (error) {
    handleLoginError(error);
  } finally {
    loading.value = false;
  }
};

// 构建登录数据
const buildLoginData = () => {
  const loginData = {
    password: loginForm.password,
  };

  // 根据选择的登录方式添加账号信息
  if (accountType.value === "email") {
    loginData.email = loginForm.email;
    loginData.username = loginForm.email; // 后端需要username字段
  } else {
    loginData.phone = loginForm.phone;
    loginData.username = loginForm.phone; // 后端需要username字段
  }

  return loginData;
};

// 执行登录操作
const performLogin = async (loginData) => {
  let success = false;
  let userData = null;

  try {
    // 调用后端登录接口
    const response = await request.post('/auth/login', loginData);
    if (response?.data) {
      success = true;
      // 处理后端返回的TokenResponse对象
      userData = {
        token: response.data.token,
        refreshToken: response.data.refreshToken,
        userInfo: response.data.userInfo,
        tokenData: response.data.tokenData
      };
    }
  } catch (error) {
    // 区分不同的错误类型，优化错误处理
    if (error.message?.includes('账号或密码错误')) {
      throw new Error('账号或密码错误');
    } else if (error.response?.status === 404 || error.message?.includes('Network Error')) {
      console.log("API不存在，使用模拟登录数据");
      
      // 模拟登录，根据用户名生成不同的用户类型
      // 这里只是为了演示，实际应该由后端返回准确的用户类型
      const username = accountType.value === "email" ? 
        loginForm.email.split('@')[0] : loginForm.phone;
      
      // 简单的模拟逻辑：根据用户名判断用户类型
      let mockUserType = 'user';
      let mockMerchantType = null;
      
      if (username.includes('admin')) {
        mockUserType = 'admin';
      } else if (username.includes('hotel')) {
        mockUserType = 'hotel';
      } else if (username.includes('cultural') || username.includes('merchant')) {
        mockUserType = 'merchant';
        mockMerchantType = 'cultural';
      }
      
      success = true;
      userData = {
        token: "mock_token_" + Date.now(),
        refreshToken: "mock_refresh_token_" + Date.now(),
        userInfo: {
          id: Date.now(),
          username: username,
          nickname: username,
          email: accountType.value === "email" ? loginForm.email : null,
          phone: accountType.value === "phone" ? loginForm.phone : null,
          userType: mockUserType,
          merchantType: mockMerchantType,
          status: 'active',
          lastLoginTime: new Date().toISOString()
        },
        tokenData: {
          userType: mockUserType,
          merchantType: mockMerchantType,
          tokenType: "token"
        }
      };
    } else {
      console.error("登录过程中发生错误:", error);
      throw error;
    }
  }

  return { success, userData };
};

// 处理登录成功
const handleLoginSuccess = (userData) => {
  // 更新用户数据
  if (userData) {
    // 保存完整的用户信息
    const userInfo = userData.userInfo || {};
    
    // 保存令牌
    userStore.setToken(userData.token);
    userStore.setUserInfo(userInfo);
    
    // 设置用户类型，使用userData中的userType
    // 后端返回的格式可能是大写，转成小写处理
    const userType = userInfo.userType?.toLowerCase() || 'user';
    userStore.setUserType(userType);
    
    // 判断是否是酒店商家
    if (userType === 'hotel') {
      userStore.setMerchantType('hotel');
    } else if (userType === 'merchant') {
      // 如果是商家，则设置商家类型
      const merchantType = userInfo.merchantType?.toLowerCase() || null;
      userStore.setMerchantType(merchantType);
    }
  }

  // 处理记住密码
  handleRememberLogin();

  ElMessage.success("登录成功");

  // 根据用户类型跳转到不同页面
  navigateAfterLogin();
};

// 处理记住登录信息
const handleRememberLogin = () => {
  if (loginForm.remember) {
    const loginInfo = {
      email: loginForm.email,
      phone: loginForm.phone,
      password: loginForm.password,
      accountType: accountType.value,
    };
    localStorage.setItem("rememberedLogin", JSON.stringify(loginInfo));
  } else {
    localStorage.removeItem("rememberedLogin");
  }
};

// 登录后导航
const navigateAfterLogin = () => {
  let redirectPath = route.query.redirect || "/";
  
  // 根据用户类型决定跳转路径
  const userType = userStore.userType?.toLowerCase();
  
  if (userType === "merchant") {
    // 根据商家类型决定跳转到哪个商家后台
    const merchantType = userStore.merchantType?.toLowerCase();
    redirectPath = merchantType === "hotel" 
      ? "/hotel-admin" 
      : "/merchant/dashboard";
  } else if (userType === "admin") {
    // 管理员跳转到管理后台
    redirectPath = "/admin/dashboard";
  } else if (userType === "hotel") {
    // 酒店用户直接跳转到酒店后台
    redirectPath = "/hotel-admin";
  }

  router.push(redirectPath);
};

// 处理登录错误
const handleLoginError = (error) => {
  console.error("登录失败:", error);
  // 提供更友好的错误信息
  if (error.message?.includes('账号或密码错误')) {
    ElMessage.error("账号或密码错误");
  } else {
    ElMessage.error(error.response?.data?.message || "登录失败，请稍后重试");
  }
};

// 生成二维码并处理扫码类型切换
const switchScanType = async (type) => {
  currentScanType.value = type.name;
  qrcodeLoading.value = true;
  qrcodeExpired.value = false;
  
  try {
    // 停止之前的轮询
    stopPollingQRCodeStatus();
    
    // 设置当前二维码
    currentQrcode.value = true;
    
    // 添加时间戳确保每次生成不同的二维码
    const qrcodeText = `您使用了${type.name}扫码登录_${Date.now()}`;
    
    // 根据不同平台生成不同颜色的二维码
    const qrcodeOptions = {
      width: 180,
      margin: 2,
      color: {
        dark: type.name === '微信' ? '#07C160' : 
              type.name === 'QQ' ? '#12B7F5' : '#000000',
        light: '#ffffff'
      }
    };
    
    // 生成二维码数据URL
    qrcodeDataUrl.value = await QRCode.toDataURL(qrcodeText, qrcodeOptions);
    qrcodeLoading.value = false;
    
    // 开始轮询扫码状态
    startPollingQRCodeStatus();
    
    // 60秒后二维码过期
    setTimeout(() => {
      if (!qrcodeExpired.value) {
        qrcodeExpired.value = true;
        stopPollingQRCodeStatus();
      }
    }, 60000);
    
  } catch (error) {
    console.error('生成二维码失败:', error);
    ElMessage.error('生成二维码失败，请稍后再试');
    qrcodeLoading.value = false;
  }
};

// 轮询扫码状态
const startPollingQRCodeStatus = () => {
  // 先清除可能存在的轮询
  stopPollingQRCodeStatus();
  
  // 实际项目中，这里应该调用后端接口检查扫码状态
  // 这里为了演示，使用模拟数据
  pollingTimer.value = setInterval(async () => {
    console.log("轮询扫码状态...");
    
    try {
      // 在实际项目中应该检查真实的扫码状态
      // const response = await request.get('/api/auth/check-scan-status', {
      //   params: { scanType: currentScanType.value }
      // });
      
      // if (response.data.scanned) {
      //   // 处理扫码成功
      //   stopPollingQRCodeStatus();
      //   handleScanSuccess(response.data);
      // }
    } catch (error) {
      console.error('检查扫码状态失败:', error);
    }
  }, 3000);
};

// 停止轮询
const stopPollingQRCodeStatus = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value);
    pollingTimer.value = null;
  }
};

// 处理扫码成功（示例函数）
const handleScanSuccess = (userData) => {
  ElMessage.success('扫码成功');
  
  // 如果需要完善信息
  if (userData.needCompleteInfo) {
    tempUserInfo.value = userData;
    showCompleteInfo.value = true;
  } else {
    // 直接登录
    const tokenType = userData.tokenData?.tokenType || 'token';
    userStore.setToken(userData.token, tokenType);
    userStore.setUserInfo(userData.userInfo);
    userStore.setUserType(userData.userInfo.userType);
    userStore.setMerchantType(userData.userInfo.merchantType);
    router.push(route.query.redirect || "/");
  }
};

// 刷新二维码
const refreshQRCode = () => {
  qrcodeExpired.value = false;
  switchScanType(scanTypes.find(type => type.name === currentScanType.value));
};

// 处理完善信息
const handleCompleteInfo = async (formData) => {
  try {
    loading.value = true;
    
    // 准备用户数据
    const completeInfoData = {
      ...formData,
      openid: tempUserInfo.value?.openid,
      provider: tempUserInfo.value?.provider,
      accessToken: tempUserInfo.value?.accessToken,
      tempToken: tempUserInfo.value?.tempToken
    };
    
    const { success, userData } = await completeUserInfo(completeInfoData);
    
    if (success) {
      // 更新用户数据
      if (userData) {
        userStore.setToken(userData.token);
        userStore.setUserInfo(userData.userInfo);
      }
      
      ElMessage.success("信息完善成功");
      showCompleteInfo.value = false;
      
      // 重定向到主页
      router.push(route.query.redirect || "/");
    }
  } catch (error) {
    console.error("完善信息失败:", error);
    ElMessage.error(error.message || "完善信息失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 完善用户信息
const completeUserInfo = async (completeInfoData) => {
  let success = false;
  let userData = null;
  
  try {
    // 调用后端API完善用户信息
    const response = await request.post('/api/auth/complete-info', completeInfoData);

    if (response?.data) {
      success = true;
      userData = {
        token: response.data.token,
        userInfo: response.data.userInfo
      };
    }
  } catch (error) {
    console.error("完善信息API调用失败:", error);
    // 如果API不存在，模拟成功
    if (error.response?.status === 404 || error.message.includes('Network Error')) {
      success = true;
      // 创建模拟用户数据
      userData = {
        token: `mock_token_${Date.now()}`,
        userInfo: {
          id: Date.now(),
          username: completeInfoData.username,
          email: completeInfoData.email,
          phone: completeInfoData.phone,
        }
      };
    } else {
      throw error;
    }
  }
  
  return { success, userData };
};

// 协议处理函数
const handleServiceAgree = () => {
  agreedToService.value = true;
  showServiceAgreement.value = false;
  ElMessage.success("您已同意服务协议");
  checkAgreements();
};

const handlePrivacyAgree = () => {
  agreedToPrivacy.value = true;
  showPrivacyAgreement.value = false;
  ElMessage.success("您已同意隐私政策");
  checkAgreements();
};

// 检查两个协议是否都同意了
const checkAgreements = () => {
  if (agreedToService.value && agreedToPrivacy.value) {
    agreedToTerms.value = true;
  }
};

// 监听两个协议的同意状态
watch([agreedToService, agreedToPrivacy], ([service, privacy]) => {
  // 当两个协议都同意时，自动勾选外部复选框
  if (service && privacy) {
    agreedToTerms.value = true;
  }
});

// 监听外部复选框状态
watch(agreedToTerms, (newValue) => {
  // 如果取消勾选外部复选框，同时取消两个协议的同意状态
  if (!newValue) {
    agreedToService.value = false;
    agreedToPrivacy.value = false;
  }
});

// 组件挂载时初始化
onMounted(() => {
  // 初始化记住的登录信息
  initRememberedLogin();
  
  // 如果是扫码登录，生成二维码
  if (loginType.value === 'qrcode') {
    nextTick(() => {
      switchScanType(scanTypes[0]);
    });
  }
});

// 组件卸载时清理资源
onUnmounted(() => {
  // 清理定时器
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  
  // 停止轮询
  stopPollingQRCodeStatus();
});

// 切换登录模式
const switchLoginMode = () => {
  loginMode.value = loginMode.value === 'password' ? 'verification' : 'password';
  // 每次切换时重置验证码相关数据
  if (loginMode.value === 'verification') {
    // 验证码模式默认使用手机号，但不强制切换
    verificationDigits.value = ["", "", "", "", "", ""];
    loginForm.verificationCode = "";
    countdown.value = 0;
    if (timer.value) {
      clearInterval(timer.value);
      timer.value = null;
    }
  }
};

// 处理验证码输入
const handleCodeInput = (index) => {
  const digit = verificationDigits.value[index];
  if (digit) {
    // 只允许输入数字
    if (!/^\d$/.test(digit)) {
      verificationDigits.value[index] = "";
      return;
    }
    // 自动跳转到下一个输入框
    if (index < 5) {
      focusInput(index + 1);
    } else {
      // 第六位输入完成后自动处理登录
      loginForm.verificationCode = verificationDigits.value.join("");
      // 短暂延迟以提供更好的用户体验
      setTimeout(async () => {
        await handleVerificationLogin();
      }, 300);
    }
  }
};

// 处理验证码删除
const handleCodeDelete = (index) => {
  if (!verificationDigits.value[index] && index > 0) {
    verificationDigits.value[index - 1] = "";
    focusInput(index - 1);
  }
};

// 处理验证码聚焦
const focusInput = (index) => {
  if (index >= 0 && index < 6) {
    codeInputs.value[index]?.focus();
  }
};

// 处理发送验证码
const handleSendVerificationCode = async () => {
  try {
    // 根据账户类型验证对应字段
    if (accountType.value === "email") {
      await loginFormRef.value?.validateField("email");
    } else {
      await loginFormRef.value?.validateField("phone");
    }
    
    loading.value = true;
    
    // 根据账户类型调用不同的验证码API
    if (accountType.value === "email") {
      // 调用邮箱验证码API
      await getEmailVerificationCode(loginForm.email, "login");
      ElMessage.success("验证码已发送至邮箱");
    } else {
      // 调用手机验证码API
      await getPhoneVerificationCode(loginForm.phone, "login");
      ElMessage.success("验证码已发送至手机");
    }
    
    startCountdown();
  } catch (error) {
    console.error("发送验证码失败:", error);
    // 根据错误码显示不同的提示信息
    if (error.response?.data?.code === 400004) {
      ElMessage.error("账号不存在，请先注册");
    } else {
      ElMessage.error(error.response?.data?.message || "发送验证码失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  // 清除可能存在的倒计时
  if (timer.value) {
    clearInterval(timer.value);
  }
  
  // 设置倒计时初始值
  countdown.value = 60;
  
  // 启动倒计时
  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer.value);
      timer.value = null;
    }
  }, 1000);
};

// 使用验证码登录
const handleVerificationLogin = async () => {
  // 检查是否同意服务条款
  if (!agreedToTerms.value) {
    showAgreementTip.value = true;
    ElMessage.warning("请先阅读并同意服务条款和隐私政策");
    return;
  }

  try {
    // 检查验证码是否已输入
    if (loginForm.verificationCode.length !== 6) {
      // 如果没有完整输入验证码，不进行任何操作
      return;
    }
    
    loading.value = true;
    
    // 构建登录数据 - 根据账户类型构建不同的参数
    const loginData = {
      verificationCode: loginForm.verificationCode,
      autoLogin: loginForm.autoLogin
    };

    // 根据账户类型添加不同的字段
    if (accountType.value === "email") {
      loginData.email = loginForm.email;
    } else {
      loginData.phone = loginForm.phone;
    }

    try {
      // 调用登录API
      const response = await request.post('/auth/verification-login', loginData);
      
      if (response?.data) {
        // 构建与密码登录格式一致的userData对象
        const userData = {
          token: response.data.token,
          refreshToken: response.data.refreshToken,
          userInfo: response.data.userInfo,
          tokenData: response.data.tokenData
        };
        
        // 使用相同的处理登录成功函数
        handleLoginSuccess(userData);
      }
    } catch (error) {
      // 模拟登录（仅用于开发环境）
      if (process.env.NODE_ENV === 'development' && 
          (error.response?.status === 404 || error.message?.includes('Network Error'))) {
        console.log("验证码登录API不存在，使用模拟数据");
        
        // 模拟逻辑与密码登录相似
        const username = accountType.value === "email" ? 
          loginForm.email.split('@')[0] : loginForm.phone;
        
        let mockUserType = 'user';
        let mockMerchantType = null;
        
        if (username.includes('admin')) {
          mockUserType = 'admin';
        } else if (username.includes('hotel')) {
          mockUserType = 'hotel';
        } else if (username.includes('cultural') || username.includes('merchant')) {
          mockUserType = 'merchant';
          mockMerchantType = 'cultural';
        }
        
        const userData = {
          token: "mock_token_" + Date.now(),
          refreshToken: "mock_refresh_token_" + Date.now(),
          userInfo: {
            id: Date.now(),
            username: username,
            nickname: username,
            email: accountType.value === "email" ? loginForm.email : null,
            phone: accountType.value === "phone" ? loginForm.phone : null,
            userType: mockUserType,
            merchantType: mockMerchantType,
            status: 'active',
            lastLoginTime: new Date().toISOString()
          },
          tokenData: {
            userType: mockUserType,
            merchantType: mockMerchantType,
            tokenType: "token"
          }
        };
        
        handleLoginSuccess(userData);
        return;
      }
      
      // 处理登录失败
      console.error("验证码登录详细错误:", error.response || error);
      
      // 根据不同的错误码显示不同的提示信息
      if (error.response?.data?.code === 400002) {
        ElMessage.error("验证码错误或已过期，请重新获取");
        // 清空验证码输入
        verificationDigits.value = ["", "", "", "", "", ""];
        loginForm.verificationCode = "";
        // 聚焦第一个输入框
        focusInput(0);
      } else if (error.response?.data?.code === 400004) {
        ElMessage.error("账号不存在，请先注册");
        // 清空验证码输入
        verificationDigits.value = ["", "", "", "", "", ""];
        loginForm.verificationCode = "";
        // 聚焦第一个输入框
        focusInput(0);
      } else {
        ElMessage.error(error.response?.data?.message || "登录失败，请稍后重试");
      }
    }
  } finally {
    loading.value = false;
  }
};

// 初始化记住的登录信息
const initRememberedLogin = () => {
  const rememberedLogin = localStorage.getItem("rememberedLogin");
  if (!rememberedLogin) return;
  
  try {
    const loginInfo = JSON.parse(rememberedLogin);
    
    // 填充表单数据
    loginForm.email = loginInfo.email || "";
    loginForm.phone = loginInfo.phone || "";
    loginForm.password = loginInfo.password || "";
    loginForm.remember = true;
    
    // 设置账户类型
    accountType.value = loginInfo.accountType || "email";
  } catch (error) {
    console.error("解析记住的登录信息失败:", error);
    // 移除无效的存储数据
    localStorage.removeItem("rememberedLogin");
  }
};
</script>

<style lang="scss" scoped>
.mail-login-page {
  @apply min-h-screen flex flex-col relative;
  background: url("@/assets/images/login-bg.jpg") center/cover fixed no-repeat;

  &::before {
    content: "";
    @apply fixed inset-0 z-0;
    background: linear-gradient(
      to bottom,
      rgba(255, 255, 255, 0.9) 0%,
      rgba(255, 255, 255, 0) 64px,
      rgba(255, 255, 255, 0) calc(100% - 64px),
      rgba(255, 255, 255, 0.9) 100%
    );

    .dark & {
      background: linear-gradient(
        to bottom,
        rgba(17, 24, 39, 0.9) 0%,
        rgba(17, 24, 39, 0.4) 64px,
        rgba(17, 24, 39, 0.4) calc(100% - 64px),
        rgba(17, 24, 39, 0.9) 100%
      );
    }
    pointer-events: none;
  }

  .top-nav {
    @apply w-full fixed top-0 left-0 z-50;

    .nav-container {
      @apply max-w-7xl mx-auto h-16 flex items-center justify-between;
      padding-left: 16px;
      padding-right: 8px;

      .nav-left {
        @apply flex items-center;

        .nav-logo {
          @apply h-14 mr-2;

          .dark & {
            filter: brightness(1.2)
              drop-shadow(0 0 8px rgba(255, 255, 255, 0.3));
          }
        }

        .brand-wrapper {
          @apply flex flex-col justify-center;

          .brand-name {
            @apply text-2xl font-bold text-gray-800 dark:text-gray-100 leading-6;
          }

          .brand-pinyin {
            @apply text-[8px] text-gray-500 dark:text-gray-400 mt-0.5;
          }
        }

        .divider {
          @apply mx-3 text-gray-300 dark:text-gray-600 text-xl;
        }

        .nav-title {
          @apply text-gray-700 dark:text-gray-200 text-lg font-medium;
        }
      }

      .nav-right {
        @apply flex items-center;
        gap: 24px;

        .nav-link {
          @apply text-sm text-gray-600 dark:text-gray-300 hover:text-[#2e74e5] dark:hover:text-[#60a5fa] transition-colors;
        }
      }
    }
  }

  .main-content {
    @apply flex-1 flex items-center relative z-10;
    padding: 80px 0;
    margin-top: 64px;

    .login-container {
      @apply w-[400px];
      margin-left: 61.8%; // 黄金分割比
      margin-right: 40px;

      .login-box {
        @apply bg-white/95 dark:bg-gray-900/95 backdrop-blur-sm rounded-2xl shadow-xl dark:shadow-2xl p-8;

        .login-type-switch {
          @apply mb-8;

          .switch-container {
            @apply w-full p-1.5 bg-gray-100 dark:bg-gray-800 rounded-xl;
          }

          .switch-track {
            @apply relative flex items-center h-14 rounded-lg;

            .switch-option {
              @apply flex-1 flex items-center justify-center gap-2 cursor-pointer z-10 transition-all duration-300;

              .el-icon {
                @apply text-2xl;
              }

              span {
                @apply text-base font-medium text-gray-600 dark:text-gray-400;
              }

              &.active {
                @apply text-[#2e74e5] dark:text-[#60a5fa];

                span {
                  @apply text-[#2e74e5] dark:text-[#60a5fa];
                }
              }
            }

            .switch-slider {
              @apply absolute top-0 left-0 w-1/2 h-full bg-white dark:bg-gray-700 rounded-lg shadow-lg;
              transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
            }
          }
        }

        .qrcode-login {
          @apply text-center;

          .qrcode-container {
            @apply relative mx-auto mb-4 rounded-lg overflow-hidden;
            width: 148px !important;
            height: 148px !important;

            .qrcode-placeholder {
              @apply w-full h-full border-2 border-dashed border-gray-300 rounded-lg 
                     flex flex-col items-center justify-center bg-gray-50/80;

              .qrcode-icon {
                @apply text-4xl text-gray-400 mb-3;
              }

              .qrcode-text {
                @apply text-sm text-gray-500;
              }
            }

            .qrcode-image {
              @apply w-full h-full object-cover;
            }

            .qrcode-mask {
              @apply absolute inset-0 bg-black/50 backdrop-blur-sm
                     flex flex-col items-center justify-center text-white gap-4;
            }
          }

          .qrcode-tip {
            @apply text-gray-600 mb-1 mt-1 text-sm;
          }

          .scan-options {
            @apply flex justify-center items-center gap-8;

            .scan-option {
              @apply flex flex-col items-center gap-2 p-3 rounded-lg cursor-pointer transition-all duration-300;

              .scan-icon-wrapper {
                @apply mb-0.5 flex items-center justify-center w-8 h-8;

                .scan-icon {
                  @apply w-6 h-6 transition-transform duration-300;
                }
              }

              &:hover {
                .scan-icon {
                  transform: scale(1.1);
                }
              }

              &.active {
                @apply bg-gray-50 dark:bg-gray-800;

                .scan-icon {
                  transform: scale(1.1);
                }
              }

              span {
                @apply text-sm text-gray-600 dark:text-gray-400;
              }

              &.wechat-scan-option {
                @apply hover:bg-[#07C160]/10 dark:hover:bg-[#07C160]/20;
                .scan-icon {
                  fill: #07c160;
                  .dark & {
                    fill: #07c160;
                  }
                }
                &.active {
                  @apply bg-[#07C160]/10 dark:bg-[#07C160]/20;
                }
              }

              &.qq-scan-option {
                @apply hover:bg-[#12B7F5]/10 dark:hover:bg-[#12B7F5]/20;
                .scan-icon {
                  fill: #12b7f5;
                  .dark & {
                    fill: #12b7f5;
                  }
                }
                &.active {
                  @apply bg-[#12B7F5]/10 dark:bg-[#12B7F5]/20;
                }
              }

              &.tiktok-scan-option {
                @apply hover:bg-gray-100 dark:hover:bg-gray-800;
                .scan-icon {
                  fill: #000000;
                  .dark & {
                    fill: #ffffff;
                  }
                }
                &.active {
                  @apply bg-gray-100 dark:bg-gray-800;
                }
              }
            }
          }
        }

        .login-form {
          :deep(.el-form-item) {
            @apply mb-6;

            &.verification-item {
              @apply mb-4; /* 减小验证码输入框下方间距 */
            }

            .el-input__wrapper {
              @apply rounded-xl bg-white dark:bg-gray-800 h-12;
              border: 1px solid #d1d5db !important;
              box-shadow: none !important;

              &:hover {
                border: 1px solid #9ca3af !important;
              }

              &.is-focus {
                border: 1px solid #2e74e5 !important;
                box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1) !important;
                background-color: white !important;

                .dark & {
                  background-color: #1f2937 !important;
                  box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.2) !important;
                }
              }

              .el-input__inner {
                @apply text-base text-gray-900 dark:text-gray-100;
                background-color: transparent !important;
                &::placeholder {
                  @apply text-gray-400 dark:text-gray-500;
                }
              }

              .el-input__prefix {
                @apply mr-1;
                .el-icon {
                  @apply text-gray-400 dark:text-gray-500 text-xl;
                }
              }
            }
          }

          .input-suffix {
            @apply absolute right-0 top-0 h-full px-4 flex items-center text-gray-500 bg-gray-100 rounded-r-xl border-l border-gray-200;
          }

          .form-options {
            @apply mb-6 flex items-center justify-between;

            .remember-checkbox,
            .auto-login-checkbox {
              @apply min-w-[80px];
              :deep(.el-checkbox__label) {
                @apply text-gray-600 dark:text-gray-300 text-sm whitespace-nowrap;
              }
              :deep(.el-checkbox__inner) {
                @apply w-4 h-4 rounded border-2 border-gray-300 dark:border-gray-600;
                &::after {
                  @apply h-2 left-[5px] top-[2px];
                }
              }
              &:deep(.is-checked) {
                .el-checkbox__inner {
                  @apply border-[#2e74e5] bg-[#2e74e5] dark:border-[#60a5fa] dark:bg-[#60a5fa];
                }
                .el-checkbox__label {
                  @apply text-[#2e74e5] dark:text-[#60a5fa];
                }
              }
            }

            .verification-login-switch {
              @apply text-sm text-gray-600 dark:text-gray-300 hover:text-[#2e74e5] dark:hover:text-[#60a5fa] cursor-pointer ml-auto;
            }
          }

          .login-btn {
            @apply w-full h-11 text-base rounded-2xl shadow-sm;
            max-width: 380px;
            margin-left: auto;
            margin-right: auto;
            display: block;
            background: linear-gradient(to right, #2e74e5, #2361c5);

            .dark & {
              background: linear-gradient(to right, #3b82f6, #2563eb);
            }

            &:hover {
              background: linear-gradient(to right, #2361c5, #1d4ed8);

              .dark & {
                background: linear-gradient(to right, #60a5fa, #3b82f6);
              }
            }

            &:active {
              @apply transform translate-y-0 shadow-md shadow-blue-500/20;
            }
          }

          .form-footer {
            @apply flex justify-center mt-6 gap-8;

            .register-link,
            .forgot-link {
              @apply text-sm text-[#2e74e5] dark:text-[#60a5fa] hover:text-[#2361c5] dark:hover:text-[#3b82f6] font-medium;
            }
          }
        }

        .terms-agreement {
          @apply text-center text-sm text-gray-500 dark:text-gray-400 mt-3 flex items-center justify-center gap-1;

          .checkbox-wrapper {
            @apply inline-flex items-center relative;
          }

          .terms-checkbox {
            :deep(.el-checkbox__inner) {
              @apply w-4 h-4 rounded border-2 border-gray-300 dark:border-gray-600;

              &::after {
                @apply h-2 left-[5px] top-[2px];
              }
            }

            &:deep(.el-checkbox__label) {
              @apply text-sm text-gray-500 dark:text-gray-400;
            }
          }

          .terms-link {
            @apply text-[#2e74e5] dark:text-[#60a5fa] hover:text-[#2361c5] dark:hover:text-[#3b82f6] font-medium;
          }
        }
      }
    }
  }

  .page-footer {
    @apply w-full py-6 text-center fixed bottom-0 left-0 z-50;
    background: transparent;

    .footer-info {
      @apply text-sm text-gray-500 dark:text-gray-400 space-x-4 relative z-10;

      .footer-link {
        @apply text-gray-500 dark:text-gray-400 hover:text-[#2e74e5] dark:hover:text-[#60a5fa] transition-colors;
      }

      .police-badge {
        @apply h-4 inline-block align-middle mr-1;

        .dark & {
          filter: brightness(0.8) contrast(1.2);
        }
      }
    }
  }
}

.account-form-item {
  :deep(.el-form-item__content) {
    @apply flex-col;
  }

  .flex {
    @apply gap-3 items-center;
  }
}

:deep(.el-input),
:deep(.el-select) {
  --el-component-size: 48px !important;
  --el-component-size-large: 48px !important;

  .el-input__wrapper {
    min-height: var(--el-component-size) !important;
    height: var(--el-component-size) !important;
    line-height: var(--el-component-size) !important;
    border: 1px solid #d1d5db !important;
    box-shadow: none !important;
    padding: 0 12px !important;

    &:hover {
      border-color: #9ca3af !important;
    }

    &.is-focus {
      border: 1px solid #2e74e5 !important;
      box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1) !important;
    }

    .el-input__inner {
      height: calc(var(--el-component-size) - 2px) !important;
      line-height: calc(var(--el-component-size) - 2px) !important;
    }
  }
}

.account-type-select {
  width: 100px !important;
}

:deep(.el-select-dropdown__item) {
  height: 48px !important;
  line-height: 48px !important;
  padding: 0 12px !important;

  .select-option-content {
    height: 48px !important;
    display: flex !important;
    align-items: center !important;
    gap: 8px !important;
  }
}

.qrcode-login {
  @apply text-center;

  .qrcode-container {
    @apply relative mx-auto mb-4 rounded-lg overflow-hidden;
    width: 148px !important;
    height: 148px !important;

    .qrcode-placeholder {
      @apply w-full h-full border-2 border-dashed border-gray-300 rounded-lg 
             flex flex-col items-center justify-center bg-gray-50/80;

      .qrcode-icon {
        @apply text-4xl text-gray-400 mb-3;
      }

      .qrcode-text {
        @apply text-sm text-gray-500;
      }
    }

    .qrcode-image {
      @apply w-full h-full object-cover;
    }

    .qrcode-mask {
      @apply absolute inset-0 bg-black/50 backdrop-blur-sm
             flex flex-col items-center justify-center text-white gap-4;
    }
  }

  .qrcode-tip {
    @apply text-gray-600 mb-4 mt-1 text-sm;
  }

  .scan-options {
    @apply flex justify-center items-center gap-8;

    .scan-option {
      @apply flex flex-col items-center gap-2 p-3 rounded-lg cursor-pointer transition-all duration-300;

      .scan-icon-wrapper {
        @apply mb-0.5 flex items-center justify-center w-8 h-8;

        .scan-icon {
          @apply w-6 h-6 transition-transform duration-300;
        }
      }

      &:hover {
        .scan-icon {
          transform: scale(1.1);
        }
      }

      &.active {
        @apply bg-gray-50 dark:bg-gray-800;

        .scan-icon {
          transform: scale(1.1);
        }
      }

      span {
        @apply text-sm text-gray-600 dark:text-gray-400;
      }

      &.wechat-scan-option {
        @apply hover:bg-[#07C160]/10 dark:hover:bg-[#07C160]/20;
        .scan-icon {
          fill: #07c160;
          .dark & {
            fill: #07c160;
          }
        }
        &.active {
          @apply bg-[#07C160]/10 dark:bg-[#07C160]/20;
        }
      }

      &.qq-scan-option {
        @apply hover:bg-[#12B7F5]/10 dark:hover:bg-[#12B7F5]/20;
        .scan-icon {
          fill: #12b7f5;
          .dark & {
            fill: #12b7f5;
          }
        }
        &.active {
          @apply bg-[#12B7F5]/10 dark:bg-[#12B7F5]/20;
        }
      }

      &.tiktok-scan-option {
        @apply hover:bg-gray-100 dark:hover:bg-gray-800;
        .scan-icon {
          fill: #000000;
          .dark & {
            fill: #ffffff;
          }
        }
        &.active {
          @apply bg-gray-100 dark:bg-gray-800;
        }
      }
    }
  }
}

.auto-complete-hint {
  @apply absolute left-0 top-0 h-full flex items-center text-gray-300 cursor-text select-none;
  padding-left: calc(2.5rem + 24px);
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .mail-login-page {
    @apply min-h-screen flex flex-col relative;
    background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);

    &::before {
      display: none;
    }

    .top-nav {
      @apply relative;
      background: rgba(255, 255, 255, 0.8);
      backdrop-filter: blur(10px);
      border-bottom: 1px solid rgba(255, 255, 255, 0.3);

      .nav-container {
        @apply px-4 h-16;

        .nav-left {
          @apply w-full justify-center;

          .nav-logo {
            @apply h-11 transition-transform duration-300;
            &:active {
              transform: scale(0.95);
            }
          }

          .brand-wrapper {
            .brand-name {
              @apply text-xl font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent;
            }
            .brand-pinyin {
              @apply text-[10px] tracking-wider text-gray-400;
            }
          }

          .divider,
          .nav-title {
            display: none;
          }
        }

        .nav-right {
          display: none;
        }
      }
    }

    .main-content {
      @apply px-4 py-8 mt-0;
      margin-top: 0;

      .login-container {
        @apply w-full mx-auto max-w-[100%] my-4;
        margin-left: auto;

        .login-box {
          @apply rounded-2xl shadow-lg p-6 mx-4;
          background: rgba(255, 255, 255, 0.9);
          backdrop-filter: blur(20px);
          border: 1px solid rgba(255, 255, 255, 0.5);

          .login-type-switch {
            @apply mb-8;

            .switch-container {
              @apply p-1 rounded-2xl;
              background: rgba(243, 244, 246, 0.8);
            }

            .switch-track {
              @apply h-12 rounded-xl relative overflow-hidden;

              .switch-slider {
                background: linear-gradient(135deg, #3b82f6 0%, #4f46e5 100%);
                box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
              }

              .switch-option {
                @apply text-sm font-medium z-20;

                .el-icon {
                  @apply text-xl;
                }

                &.active {
                  @apply text-white;
                  
                  span {
                    @apply text-white;
                  }
                }
              }
            }
          }

          .qrcode-login {
            .qrcode-container {
              width: 200px !important;
              height: 200px !important;
              @apply mx-auto rounded-2xl overflow-hidden shadow-md;
              border: 1px solid rgba(255, 255, 255, 0.8);

              .qrcode-placeholder {
                @apply bg-gradient-to-br from-gray-50 to-gray-100;
              }

              .qrcode-mask {
                background: rgba(0, 0, 0, 0.7);
                backdrop-filter: blur(4px);

                p {
                  @apply text-lg font-medium mb-2;
                }

                .el-button {
                  @apply border-0 bg-white/90 text-gray-800 font-medium hover:bg-white;
                }
              }
            }

            .qrcode-tip {
              @apply text-gray-500 font-medium my-6;
            }

            .scan-options {
              @apply gap-6 flex-wrap justify-center;
              padding: 0 12px;

              .scan-option {
                @apply basis-1/4 p-3 rounded-xl transition-all duration-300;

                .scan-icon-wrapper {
                  @apply mb-2;
                }

                .scan-icon {
                  @apply text-2xl mb-2;
                }

                span {
                  @apply text-xs font-medium;
                }

                &:active {
                  transform: scale(0.95);
                }
              }
            }
          }

          .login-form {
            :deep(.el-form-item) {
              @apply mb-5;

              .el-input__wrapper {
                @apply h-12 rounded-xl;
                background: rgba(243, 244, 246, 0.8) !important;
                border: 1px solid rgba(255, 255, 255, 0.8) !important;
                transition: all 0.3s ease;

                &:hover {
                  background: rgba(243, 244, 246, 0.9) !important;
                }

                &.is-focus {
                  @apply bg-white !important;
                  border: 1px solid #3b82f6 !important;
                  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1) !important;
                }

                .el-input__inner {
                  @apply text-base font-medium;
                  &::placeholder {
                    @apply text-gray-400 font-normal;
                  }
                }
              }
            }

            .form-options {
              @apply mb-6 flex items-center justify-between;

              .remember-checkbox,
              .auto-login-checkbox {
                @apply mb-0;
                :deep(.el-checkbox__label) {
                  @apply text-gray-600 font-medium;
                }
              }
              
              .verification-login-switch {
                @apply ml-auto text-blue-600 font-medium;
              }
            }

            .login-btn {
              @apply h-12 text-base font-semibold rounded-xl;
              background: linear-gradient(135deg, #3b82f6 0%, #4f46e5 100%);
              box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
              transition: all 0.3s ease;

              &:active {
                transform: translateY(1px);
                box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15);
              }
            }

            .form-footer {
              @apply mt-6 gap-6;

              a {
                @apply text-sm font-medium text-gray-600;
                &:active {
                  @apply text-blue-600;
                }
              }
            }
          }

          .terms-agreement {
            @apply mt-6 text-xs flex-wrap justify-center;

            :deep(.el-checkbox__label) {
              @apply text-gray-500 font-medium;
            }

            .terms-link {
              @apply font-semibold text-blue-600;
            }
          }
        }
      }
    }
  }

  .account-form-item {
    .flex {
      @apply flex-col gap-3;
    }

    .account-type-select {
      @apply w-full order-first mb-2;
      width: 100% !important;

      :deep(.el-input__wrapper) {
        background: rgba(243, 244, 246, 0.8) !important;
      }
    }
  }

  :deep(.el-input),
  :deep(.el-select) {
    --el-component-size: 48px !important;
    --el-component-size-large: 48px !important;
  }

  .auto-complete-hint {
    @apply text-gray-300 font-medium;
    padding-left: calc(2rem + 20px);
  }
}

.terms-agreement {
  @apply text-center text-sm text-gray-500 dark:text-gray-400 mt-3 flex items-center justify-center gap-1;

  .checkbox-wrapper {
    @apply inline-flex items-center relative;
  }

  .terms-checkbox {
    :deep(.el-checkbox__inner) {
      @apply w-4 h-4 rounded border-2 border-gray-300 dark:border-gray-600;

      &::after {
        @apply h-2 left-[5px] top-[2px];
      }
    }

    &:deep(.el-checkbox__label) {
      @apply text-sm text-gray-500 dark:text-gray-400;
    }
  }

  .terms-link {
    @apply text-[#2e74e5] dark:text-[#60a5fa] hover:text-[#2361c5] dark:hover:text-[#3b82f6] font-medium;
  }
}

:deep(.agreement-tooltip) {
  @apply bg-red-50 border border-red-100;

  .el-tooltip__content {
    @apply text-red-500 text-sm px-3 py-1.5;
  }
}

/* 社交媒体图标样式 */
.wechat-icon {
  fill: #07c160;
}

.qq-icon {
  fill: #12b7f5;
}

.tiktok-icon {
  fill: #000000;
}

/* 增加微信和QQ登录的特定样式 */
#wx-qrcode-container, #qq-qrcode-container {
  @apply w-full h-full flex items-center justify-center;
  
  :deep(iframe) {
    width: 100% !important;
    height: 100% !important;
  }
}

#qq-login-btn {
  @apply w-full h-full relative;
  overflow: hidden;
  
  :deep(.qc_login_container) {
    width: 100% !important;
    height: 100% !important;
    position: relative;
  }
}

/* QQ登录额外样式 */
:deep(.qc_login_frame) {
  width: 100% !important;
  height: 100% !important;
}

/* 二维码容器额外样式 */
.qrcode-container {
  @apply relative mx-auto mb-4 rounded-lg overflow-hidden;
  width: 180px !important;
  height: 180px !important;
  background-color: #fff;
  border: 1px solid #e5e7eb;
}

/* 真实二维码样式 */
.real-qrcode {
  @apply w-full h-full object-contain;
}

/* 二维码容器样式 */
.qrcode-image {
  @apply relative w-full h-full flex items-center justify-center;
}

/* 验证码输入框样式 */
.verification-code-input {
  @apply flex gap-2 justify-center;
  max-width: 380px;
  margin: 4px auto; /* 减小上下边距 */

  .code-digit {
    @apply w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 text-center text-2xl
           focus:border-blue-500 dark:focus:border-blue-400 focus:outline-none transition-all duration-300
           bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm shadow-sm text-gray-900 dark:text-gray-100;

    &:focus {
      @apply shadow-md ring-2 ring-blue-100 dark:ring-blue-900;
    }

    &:hover {
      @apply border-gray-300 dark:border-gray-600 shadow-md;
    }
  }
}

.verification-login-switch {
  @apply text-sm text-[#2e74e5] dark:text-[#60a5fa] hover:text-[#2361c5] dark:hover:text-[#3b82f6] cursor-pointer font-medium;
}

.verification-tip-box {
  @apply flex items-center gap-2 mt-2 mb-4;
  color: #ff7b7b;
}

.tip-icon {
  @apply text-lg;
}

.tip-text {
  @apply text-sm;
}

.verification-send-btn {
  @apply h-12 text-sm font-medium rounded-xl transition-all duration-300 min-w-[100px] px-4;
  background: linear-gradient(to right, #2e74e5, #2361c5);
  border: none;
  white-space: nowrap;

  .dark & {
    background: linear-gradient(to right, #3b82f6, #2563eb);
  }

  &:hover:not(:disabled) {
    @apply transform -translate-y-0.5 shadow-md;
  }

  &:disabled {
    @apply opacity-70 cursor-not-allowed;
  }
}

.submit-btn, .send-code-btn {
  @apply w-full h-11 text-base rounded-2xl shadow-sm;
  max-width: 380px;
  margin-left: auto;
  margin-right: auto;
  display: block;
  background: linear-gradient(to right, #2e74e5, #2361c5);

  .dark & {
    background: linear-gradient(to right, #3b82f6, #2563eb);
  }

  &:hover {
    background: linear-gradient(to right, #2361c5, #1d4ed8);

    .dark & {
      background: linear-gradient(to right, #60a5fa, #3b82f6);
    }
  }
}
</style>
